//
//  XOHomePlatformCategoryViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2018/3/19.
//  Copyright © 2018年 lifayu. All rights reserved.
//

#import "XOHomePlatformCategoryViewController.h"

#import "EJSHomeBannerView.h"
#import "EJSHomeCategoryHeaderReusableView.h"
#import "EJSHomeGoodCollectionViewCell.h"
#import "EJSCategoryCollectionViewCell.h"
#import "EJSHorizontalGoodsCCell.h"
#import "EJSGoodsListViewController.h"
#import "EJSGoodsDetailInfoViewController.h"

#import "EJSAdRequest.h"
#import "XOPlatformCategoryListRequest.h"
#import "EJSGoodsListRequest.h"
#import "EJSGoodsAddCartRequest.h"
#import "XOShoppingCartListRequest.h"
#import "XOShoppingCartListModel.h"
#import "XOShopViewModel.h"
#import "XOGoodsCartListView.h"

@interface XOHomePlatformCategoryViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate,EJSHomeGoodCollectionViewCellDelegate,XOSHoppingCartViewProtocol>{
    NSInteger _currentPage;
    NSIndexPath * _currentIndex;
}

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) EJSHomeBannerView *bannerView;
@property (strong, nonatomic) NSMutableArray *categoryAdList;
@property (strong, nonatomic) NSMutableArray *hotCategoryList;//热门分类
@property (strong, nonatomic) NSMutableArray *hotGoodsList;//热销单品
@property (strong, nonatomic) NSMutableArray *inSeasonGoodsList;//当季新品
@property (strong, nonatomic) NSMutableArray *categoryGoodsList;//分类商品
StrongProperty XOShoppingCartListModel *shoppingCartListModel;
@property (strong, nonatomic) XOShoppingCartModel *shopCartModel;
@end

@implementation XOHomePlatformCategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentPage = 1;
    [self getCategoryAdRequest];
    [self getHotCategoryList];
    [self getCategoryGoods: @"1"];
    [self getCategoryGoods: @"2"];
    [self getCategoryGoods];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self getCartList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configOwnViews
{
    [self.collectionView registerClass:[EJSHomeCategoryHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSHomeCategoryHeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHomeGoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"XOSHomeGoodCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSCategoryCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"EJSCategoryCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHorizontalGoodsCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell"];
    
    self.bannerView = [[EJSHomeBannerView alloc] initWithFrame:CGRectMake(0, -k_EJSHomeBannerViewHeight, ScreenWidth, k_EJSHomeBannerViewHeight)];
    self.bannerView.cycleScrollView.delegate = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [self getCategoryAdRequest];
        [self getHotCategoryList];
        [self getCategoryGoods: @"1"];
        [self getCategoryGoods: @"2"];
        [self getCategoryGoods];
    }];

    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self getCategoryGoods];

    }];

    self.collectionView.mj_header.ignoredScrollViewContentInsetTop = 0;
    [self.collectionView addSubview:self.bannerView];
}

- (void)setCategoryAdList:(NSMutableArray *)categoryAdList{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
    
    if(_categoryAdList != categoryAdList){
        _categoryAdList = categoryAdList;
        NSMutableArray *adImageUrls = [NSMutableArray array];
        for (EJSAdModel *model in _categoryAdList) {
            [adImageUrls addObject:model.img?model.img:@""];
        }
        [self.bannerView.cycleScrollView setImageURLStringsGroup:adImageUrls];
        if(_categoryAdList.count > 0){
            [self.collectionView addSubview:self.bannerView];
            self.collectionView.contentInset = UIEdgeInsetsMake(k_EJSHomeBannerViewHeight, 0, 0, 0);
            self.collectionView.mj_header.ignoredScrollViewContentInsetTop = k_EJSHomeBannerViewHeight;
        }else{
            [self.bannerView removeFromSuperview];
            self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            self.collectionView.mj_header.ignoredScrollViewContentInsetTop = 0;
        }
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    if(index < self.categoryAdList.count){
        EJSAdModel *model = self.categoryAdList[index];
        if([model.linkType isEqualToString:@"goods"]){
            EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] initWithNibName:@"EJSGoodsDetailInfoViewController" bundle:nil];
            goodsDetailVC.goodsId = model.linkId;
            [self.navigationController pushViewController:goodsDetailVC animated:YES];
        }else if([model.linkType isEqualToString:@"category"]){
            XOPlatformCategoryModel *categoryModel = [XOPlatformCategoryModel new];
            categoryModel.sortId = model.linkId;
            categoryModel.sortName = model.adName;
            EJSGoodsListViewController *goodsListVC = [[EJSGoodsListViewController alloc] initWithNibName:@"EJSGoodsListViewController" bundle:nil];
            goodsListVC.platformCategoryModel = categoryModel;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == 0){
        return self.hotCategoryList.count;
    }else if (section == 1){
        if(self.hotGoodsList.count > 0){
            return 1;
        }
        return 0;
    }
    else if (section == 2){
        if(self.inSeasonGoodsList.count > 0){
            return 1;
        }
        return 0;
    }else if (section == 3){
        return self.categoryGoodsList.count;
    }
    return 0;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
    {
        EJSCategoryCollectionViewCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSCategoryCollectionViewCell" forIndexPath:indexPath];
        [ccell setPlatformCategoryModel:self.hotCategoryList[indexPath.item]];
        return ccell;
    }else if (indexPath.section == 1){
        EJSHorizontalGoodsCCell *horizontalGoodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell" forIndexPath:indexPath];
        [horizontalGoodsCell setGoodsList:self.hotGoodsList];
        return horizontalGoodsCell;
    }
    else if (indexPath.section == 2){
        EJSHorizontalGoodsCCell *horizontalGoodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell" forIndexPath:indexPath];
        [horizontalGoodsCell setGoodsList:self.inSeasonGoodsList];
        return horizontalGoodsCell;
    }else{
        EJSHomeGoodCollectionViewCell *goodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XOSHomeGoodCollectionViewCell" forIndexPath:indexPath];
//        [goodsCell setGoodsModel:self.categoryGoodsList[indexPath.item]];
        EJSGoodsModel *model = self.categoryGoodsList[indexPath.item];
        goodsCell.delegate = self;
        goodsCell.goodModel = model;
        goodsCell.shoppingCartListModel = self.shopCartModel;
        goodsCell.borderColor = UIColorFromRGB(0xE9E9E9);
        goodsCell.borderWidth = 0.5;
    
        return goodsCell;
    }
    return [UICollectionViewCell new];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    EJSHomeCategoryHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSHomeCategoryHeaderReusableView" forIndexPath:indexPath];
    if(indexPath.section == 0){
        headerView.titleLabel.text = @"= 热门分类 =";
    }else if (indexPath.section == 1){
        headerView.titleLabel.text = @"= 热销单品 =";
    }else if (indexPath.section == 2){
        headerView.titleLabel.text = @"= 当季新品 =";
    }else if (indexPath.section == 3){
        headerView.titleLabel.text = @"= 推荐商品 =";
    }
    return headerView;
}
#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//    if(section == 0){
//        if(self.hotCategoryList.count > 0){
//            return UIEdgeInsetsMake(0, 15, 0, 15);
//        }
//    }
//    else if (section == 3){
//        if(self.inSeasonGoodsList.count > 0){
//            return UIEdgeInsetsMake(0, 15, 0, 15);
//        }
//    }
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    CGFloat spacing = 15.0f;
    if(section == 0){
        spacing = 21;
    }else if (section == 1 || section == 2){
        spacing = 0;
    }
    else if (section == 3){
        spacing = 15;
    }
    return spacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    CGFloat spacing = 15.0f;
    if(section == 0){
        spacing = (int)((collectionView.width - 50*4 - 15*2)/3);
    }else if (section == 1 || section == 2){
        spacing = 0;
    }
    else if (section == 3){
        spacing = 15;
    }
    return spacing;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = 0.0f;
    CGFloat height = 0.0f;
    if(indexPath.section == 0){
        width = 50;
        height = 80;
    }else if (indexPath.section == 1 || indexPath.section == 2){
        width = ScreenWidth;
        height = 166;
    }else if (indexPath.section == 3){
         width = (ScreenWidth - 45)/2;
         height = 170 + ScreenWidth/2.0 * (300/375.0);
    }
    return CGSizeMake(width, height);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if(section == 0){
        if(self.hotCategoryList.count > 0){
            return CGSizeMake(ScreenWidth, 70);
        }
    }else if (section == 1){
        if(self.hotGoodsList.count > 0){
            return CGSizeMake(ScreenWidth, 70);
        }
    }
    else if (section == 2){
        if(self.inSeasonGoodsList.count > 0){
            return CGSizeMake(ScreenWidth, 70);
        }
    }else if (section == 3){
        if(self.categoryGoodsList.count > 0){
            return CGSizeMake(ScreenWidth, 70);
        }
    }
    return CGSizeZero;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
    {
        EJSGoodsListViewController *goodsListVC = [[EJSGoodsListViewController alloc] initWithNibName:@"EJSGoodsListViewController" bundle:nil];
        goodsListVC.platformCategoryModel = self.hotCategoryList[indexPath.item];
        [self.navigationController pushViewController:goodsListVC animated:YES];
    }else if (indexPath.section == 3){
        
        EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] initWithNibName:@"EJSGoodsDetailInfoViewController" bundle:nil];
        EJSGoodsModel *goodModel = self.categoryGoodsList[indexPath.row];
        goodsDetailVC.goodsId = goodModel.spuId;

//        EJSGoodsSkuModel *skuModel = goodModel.skus.firstObject;
//        [goodsDetailVC setDatasWith:self.categoryGoodsList and:skuModel.shopId and:[NSIndexPath indexPathForRow:indexPath.row inSection:0] andCurrentGoodModel:goodModel];
//        goodsDetailVC.delegate = self;
        [self.navigationController pushViewController:goodsDetailVC animated:YES];

    }
}

#pragma mark - Request
- (void)getCategoryAdRequest{
    FlyWeakSelf
    EJSAdRequest *req = [EJSAdRequest new];
    req.type = @"category";
    req.sortId = self.sortId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.categoryAdList = response.data;
    } failHandler:^(BaseResponse *response) {
        
    }];
}

- (void)getHotCategoryList{
    FlyWeakSelf
    XOPlatformCategoryListRequest *req = [XOPlatformCategoryListRequest new];
    req.type = @"children";
    req.parentId = self.sortId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.hotCategoryList = response.data;
        [self.collectionView.mj_footer endRefreshing];
        [self.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}

//label 1新品 2热门
- (void)getCategoryGoods:(NSString *)label{
    FlyWeakSelf
    EJSGoodsListRequest *req = [EJSGoodsListRequest new];
    req.sortId = self.sortId;
    req.labelId = label;
    req.page = @(_currentPage).stringValue;
    req.pageLimit = @"500";
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        EJSGoodsListModel *listModel = response.data;
        if(label.integerValue == 1){
            if(_currentPage == 1){
                weakSelf.inSeasonGoodsList = [NSMutableArray arrayWithArray:listModel.list];
            }else{
                [weakSelf.inSeasonGoodsList addObjectsFromArray:listModel.list];
            }
            
        }else{
            if(_currentPage == 1){
                weakSelf.hotGoodsList = [NSMutableArray arrayWithArray:listModel.list];
            }else{
                [weakSelf.hotGoodsList addObjectsFromArray:listModel.list];
            }
        }
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}

-(void)setShoppingCartListModel:(XOShoppingCartListModel *)shoppingCartListModel {
    _shoppingCartListModel = shoppingCartListModel;
    self.shopCartModel = nil;
    if (self.categoryGoodsList.count > 0) {
        EJSGoodsModel *goodModel = self.categoryGoodsList[0];
        EJSGoodsSkuModel *sku = goodModel.skus.firstObject;
        NSString *shopId = sku.shop_id == nil ? sku.shopId : sku.shop_id;
        [XOShopViewModel shared].shopId = shopId;
        for (XOShoppingCartModel *cart in _shoppingCartListModel.list) {
            if ([cart.shopId isEqualToString: shopId]) {
                self.shopCartModel = cart;
            }
        }
        [self.collectionView reloadData];
    }else {
        return;
    }

}

/// 获取购物车列表
- (void)getCartList{
    
//    if(![EJSUserTokenModel userTokenModel]){
//        return;
//    }
//    FlyWeakSelf
//    XOShoppingCartListRequest *req = [XOShoppingCartListRequest new];
//    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
//        weakSelf.shoppingCartListModel = response.data;
//        [weakSelf.collectionView reloadData];
//    } failHandler:^(BaseResponse *response) {
//        [[HUDHelper sharedInstance] tipMessage: response.message];
//        weakSelf.shoppingCartListModel = nil;
//        [weakSelf.collectionView reloadData];
//    }];
    
    if(![EJSUserTokenModel userTokenModel]){
        return;
    }
    FlyWeakSelf
    [[XOShopCartViewModel shared] updateCartList:^(XOShoppingCartListModel * _Nonnull response) {
        if (response) {
            weakSelf.shoppingCartListModel = response;
        }else {
            [weakSelf.collectionView reloadData];
        }
    }];

}

    //MARK: - 分类下的商品
- (void)getCategoryGoods{
    FlyWeakSelf
    EJSGoodsListRequest *req = [EJSGoodsListRequest new];
    req.sortId = self.sortId;
    req.page = @(_currentPage).stringValue;
    req.pageLimit = @"500";
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        EJSGoodsListModel *listModel = response.data;
        if(_currentPage == 1){
            weakSelf.categoryGoodsList = [NSMutableArray arrayWithArray:listModel.list];
        }else{
            if (listModel.list.count == 0) {
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }else {
                  [weakSelf.categoryGoodsList addObjectsFromArray:listModel.list];
            }
        }
        [weakSelf getCartList];
    } failHandler:^(BaseResponse *response) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

//- (void)goodsCell:(EJSGoodsCCell *)cell addGoodsNum:(EJSGoodsModel *)model {
//    _currentIndex = [self.collectionView indexPathForCell:cell];
//    model.addCartNum = @(model.addCartNum.intValue + model.minToBuy.intValue);
//    [self addToCartReq: model];
//}

- (void)addToCartReq:(EJSGoodsModel *)model{
    EJSGoodsAddCartRequest *req = [EJSGoodsAddCartRequest new];
    EJSGoodsSkuModel* skuModel =  model.skus.firstObject;
    req.skuId = skuModel.sku_id;
    req.num = model.minToBuy;
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"加入购物车成功"];
        [weakSelf.collectionView reloadItemsAtIndexPaths:@[_currentIndex]];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
        model.addCartNum = @(model.addCartNum.intValue - model.minToBuy.intValue);
    }];
}


#pragma mark - goosCellDelegate cell代理
- (BOOL)homeGoodCellIsLogin {
    return [self userIsLogin];
}

- (void)homeGoodUpdateShopCartWith:(XOShoppingCartModel *)cartListModel {
    self.shopCartModel = cartListModel;
}

- (void)homeGoodCellWillShowCartView:(XOShoppingCartModel *)cartModel andCurrentSpuId:(NSString *)spuId {
    NSMutableArray *tempArray = [NSMutableArray new];
    for (EJSShoppingCartGoodsModel *goodModel in cartModel.carts) {
        if ([goodModel.spuId isEqualToString: spuId]) {
            [tempArray addObject:goodModel];
        }
    }

    if (!(tempArray.count > 0)) {
        [[HUDHelper sharedInstance]tipMessage:@"本店铺暂无添加任何商品" delay:1.0];
        return;
    }

    [XOShopViewModel shared].shopCartGoodsList = tempArray;
    [XOShopViewModel shared].spuId = spuId;
    XOGoodsCartListView* cartView = [XOGoodsCartListView showSelectGoodsCartView: cartModel withCartList:_shoppingCartListModel];
    cartView.delegate = self;
}

#pragma mark - shopCartViewDelegate
- (void)shoppingCartViewWillDisapear {
    [self getCartList];
}

- (void)goodsDetailWillDisappearWithIndex:(NSIndexPath *)indexPath {
    [[XOShopCartViewModel shared] updateCartList:^(XOShoppingCartListModel * _Nonnull response) {
        
    }];

}

@end
